[CmdletBinding()]
param (
    [Parameter()]
    [string]
    $Name,

    # Beta
    [Parameter()]
    [switch]
    $Beta,

    # Debug
    [Parameter()]
    [switch]
    $EnableDebug
)

$SRC_LOCATION = $PWD

try {
    if ($EnableDebug) {
        $DebugPreference = 'Continue'
    }
    else {
        $DebugPreference = 'SilentlyContinue'
    }
    
    $GIT_TAG = git describe --tags

    $IMAGE_NAME = $Name
    $IMAGE_TAG = $GIT_TAG

    if (-not($LASTEXITCODE -eq 0)) {
        Write-Error "exit: $($LASTEXITCODE)"
        exit $LASTEXITCODE
    }

    if ([string]::IsNullOrWhiteSpace($Name)) {
        Write-Error "参数:Name 必填"
        exit 1
    }

    $TARGET_PATH = Join-Path $SRC_LOCATION $Name

    if (Test-Path $TARGET_PATH) {

        $TARGET_PATH = (Get-Item -Path $TARGET_PATH -Verbose).FullName
        Write-Debug $TARGET_PATH

        Set-Location $TARGET_PATH

        if ($Beta) {
            $IMAGE_TAG += "-beta"
        }

        $DOCKER_IMAGES = docker images
        $DOCKER_IMAGES = $DOCKER_IMAGES[1..($DOCKER_IMAGES.Length - 1)]
        $DOCKER_IMAGES = $DOCKER_IMAGES
        | ForEach-Object {
            $parts = $([System.Text.RegularExpressions.Regex]::Split($_, "[\s]+"))
            $obj = [PSCustomObject]@{
                REPOSITORY = $parts[0]
                TAG        = $parts[1]
                ID         = $parts[2]
            }

            Write-Output $obj
        }
        | Where-Object {
            ($_.REPOSITORY -eq $IMAGE_NAME) -and ($_.TAG -match "$($IMAGE_TAG)\.[\d]+")
        }

        $DOCKER_IMAGES | Format-Table

        $IMAGE_INDEX = $DOCKER_IMAGES.Length + 1;
        
        $IMAGE_TAG += ".$($IMAGE_INDEX)"

        $IMAGE_NAME_WITH_TAG = "$($IMAGE_NAME):$($IMAGE_TAG)"
        $IMAGE_NAME_WITH_TAG_LATEST = "$($IMAGE_NAME):latest"

        $BUILD_COMMAND = "docker build -t $($IMAGE_NAME_WITH_TAG) ."
        $UPDATE_LATEST_COMMAND = "docker tag $($IMAGE_NAME_WITH_TAG) $($IMAGE_NAME_WITH_TAG_LATEST)"
        
        Write-Debug $BUILD_COMMAND
        Invoke-Expression -Command $BUILD_COMMAND -ErrorAction Stop

        Write-Debug $UPDATE_LATEST_COMMAND
        Invoke-Expression -Command $UPDATE_LATEST_COMMAND -ErrorAction Stop
    }
    else {
        Write-Error "未找到目录: $($TARGET_PATH)"
    }
}
finally {
    Set-Location $SRC_LOCATION
}